package utils

import (
	"log"
	"net"
	"os/exec"
	"strings"
)

func ParseIPHeader(packet []byte) (srcIP, dstIP net.IP) {
	if len(packet) < 20 {
		return nil, nil
	}

	// 获取IP版本 (第一个字节的高4位)
	version := packet[0] >> 4
	switch version {
	case 4:
		// IPv4
		if len(packet) < 20 {
			return nil, nil
		}
		srcIP = net.IP(packet[12:16])
		dstIP = net.IP(packet[16:20])
	case 6:
		// IPv6
		if len(packet) < 40 { // IPv6 header 固定40字节
			return nil, nil
		}
		srcIP = net.IP(packet[8:24])
		dstIP = net.IP(packet[24:40])
	default:
		return nil, nil
	}
	return
}

// ExecuteCommands executes a string of commands separated by semicolons
// Example: "iptables -A FORWARD -i tun0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE"
func ExecCmd(cmd string) {
	// Split commands by semicolon and trim spaces
	commands := strings.Split(cmd, ";")
	for _, command := range commands {
		command = strings.TrimSpace(command)
		if command == "" {
			continue
		}

		args := strings.Fields(command)
		cmd_ := exec.Command(args[0], args[1:]...)

		// Capture both stdout and stderr
		output, err := cmd_.CombinedOutput()
		if err != nil {
			log.Printf("Failed to execute command '%s': %v\nOutput: %s", command, err, string(output))
			continue
		}
		log.Printf(" executed command: %s", command)
	}
}
